package com.epam.Parsers;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import com.epam.Xml.Hotel;
import com.epam.Xml.TouristVoucher;
import com.epam.Xml.TouristVouchers;

public class JAXBParser {

	private static InputStream file = JAXBParser.class.getClassLoader().getResourceAsStream("NewFile.xml");
	private static InputStream schemaFile = JAXBParser.class.getClassLoader().getResourceAsStream("NewXMLSchema1.xsd");
	public static Logger log = Logger.getLogger(JAXBParser.class);

	public static void marshallXML(String name,
			TouristVouchers<TouristVoucher> w, String path) throws JAXBException, FileNotFoundException {

		JAXBContext jc = JAXBContext.newInstance(TouristVoucher.class,
				TouristVouchers.class, Hotel.class);

		Marshaller marshaller = jc.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

		QName qName = new QName(name);
		JAXBElement<TouristVouchers> jaxbElement = new JAXBElement<TouristVouchers>(
				qName, TouristVouchers.class, w);
		marshaller.marshal(jaxbElement, new File(path));

	}

	public static List<TouristVoucher> unmarshallXML() throws JAXBException {

		JAXBContext jc = JAXBContext.newInstance(TouristVoucher.class,
				TouristVouchers.class, Hotel.class);

		Unmarshaller unmarshaller = jc.createUnmarshaller();
		StreamSource ss = new StreamSource(file);
		TouristVouchers<TouristVoucher> wrapper = (TouristVouchers<TouristVoucher>) unmarshaller.unmarshal(ss, TouristVouchers.class).getValue();
		return wrapper.getVouchers();
	}

	public static void checkXML(String file, String schemaFile) throws IOException {
		Source xmlFile = new StreamSource(file);
		Source schemaFileSource = new StreamSource(schemaFile);
		try {
			SchemaFactory s = SchemaFactory
					.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			Schema schema = s.newSchema(schemaFileSource);
			Validator validator = schema.newValidator();
			validator.validate(xmlFile);
			log.info("XML file is valid");
		} catch (SAXException e) {
			log.info("XML file is not valid");
			e.printStackTrace();
		}
	}

	}

